<template>
  <div class="main-content">
    <div class="row">
      <div class="col-sm-4 col-md-3">
        <ul class="template-title-fl">
          <li><button type="button"
                    class="btn btn-default btn-theme addBtn"
                    v-on:click="openOrgModal('A')">新增</button></li>
          <li><button type="button"
                    class="btn btn-default btn-theme"
                    v-on:click="openOrgModal('U')">修改</button></li>
          <li><button type="button"
                    class="btn btn-default btn-theme"
                    v-on:click="delOrg">删除</button></li>
          <li><button type="button"
                    class="btn btn-default btn-theme"
                    v-on:click="uploadExcel(1)">批量导入</button></li>
          <li><button type="button"
                    class="btn btn-default btn-theme"
                    v-on:click="mergeModal(0)">合并</button></li>
          <li><button type="button"
                    class="btn btn-default btn-theme"
                    v-on:click="mergeModal(1)">转移</button></li>
        </ul>
        <div class="table-filter">
          <ul class="template-title-fls"
              style="padding: 10px 0 0 10px;">
            <li><input type="text"
                     v-model="searchDeptModel.deptName"
                     id="key"
                     class="form-control-sm"
                     style="width:100%;"
                     placeholder="请输入机构名称" /></li>
            <li><button type="button"
                      class="btn btn-default btn-theme"
                      v-on:click="queryDetpByDeptName()">查询</button></li>
          </ul>
          <ul id="orgTree"
              class="ztree"></ul>
          <span id="orgTreeText"
                style="padding-left: 10px;font-weight: bolder;display: none;">无查询结果</span>
        </div>
      </div>
      <div class="col-sm-8 col-md-9">
        <form id="searchForm">
          <ul class="template-title-fls">
            <li><input type="text"
                     v-model="searchUserModel.accountName"
                     name="accountName"
                     class="form-control-sm"
                     placeholder="姓名" /></li>
            <li><input type="text"
                     v-model="searchUserModel.phone"
                     class="form-control-sm"
                     placeholder="手机号码" /></li>
            <li>
              <select class="form-control-sm"
                      style="float:left"
                      v-model="searchUserModel.accountType">
                <option value="">是否为超管</option>
                <option value="0">是</option>
                <option value="1">否</option>
              </select>
            </li>
            <li><button type="button"
                      class="btn btn-default btn-theme addBtn2"
                      v-on:click="openUserModal('A', '')">新增</button></li>
            <li><button type="button"
                      class="btn btn-default btn-theme"
                      v-on:click="loadPartnerByDept(1)">查询</button></li>
            <li><button type="button"
                      class="btn btn-default btn-theme"
                      v-on:click="uploadExcel(2)">批量导入</button></li>
            <li><button type="button"
                      class="btn btn-default btn-theme"
                      v-on:click="showQrCode()"
                      v-res="{code:'menu_0003_0001_0012'}">生成当前机构注册二维码</button></li>
          </ul>
        </form>
        <div class="table-responsive">
          <table class="table table-striped table-bordered min-width-790">
            <thead>
              <tr>
                <th width="7%">序号</th>
                <th width="10%">公司代码</th>
                <th width="15%">员工姓名</th>
                <th width="15%">联系电话</th>
                <th width="10%">部门</th>
                <th width="10%">角色</th>
                <th width="5%">状态</th>
                <th width="28%">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, index) in rows"
                  :key="index">
                <td>{{index + 1}}</td>
                <td>{{row.companyCode}}</td>
                <td>{{row.accountName}}</td>
                <td>{{row.phone}}</td>
                <td>{{row.dempName}}</td>
                <td v-if="row.accountType == 0"
                    style="color: red;">超级管理员</td>
                <td v-else>{{ row.roleName }}</td>
                <td><span :class="[{stateOne: row.status==1, stateTwo: row.status==0}]">{{row.status==1?"在用":"禁用"}}</span></td>
                <td>
                  <button type="button"
                          class="btnA edit"
                          v-on:click="openUserModal('U', row.id)">编辑</button>
                  <button type="button"
                          class="btnA delete-btn"
                          v-on:click="updateUserStatus(row.id, row.status)">{{row.status==1?"禁用":"启用"}}</button>
                  <button type="button"
                          class="btnA initial"
                          v-on:click="initPass(row.id);"
                          data-toggle="modal"
                          data-target="#myModal">重置密码</button>
                  <button type="button"
                          class="btnA delete-btn"
                          v-if="accountType == 0"
                          v-on:click="deleteUser(row.id);">删除</button>
                  <button type="button"
                          class="btnA edit"
                          v-if="accountType == 0"
                          v-on:click="openDept(row.id,row.accountName);">调整部门</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div id="laypage_div"></div>
      </div>
    </div>
    <addOrgModal v-bind:orgModal="orgInfo"
                 v-on:saveOrgListener='saveOrgReturn'></addOrgModal>
    <addUserModal v-bind:userModal="userInfo"
                  v-on:saveUserListener='saveUserReturn'></addUserModal>
    <uploadExcelModal ref="uploadExcelRef"
                      v-bind:excelModal="excelInfo"
                      v-on:saveExcelListener='saveOrgReturn'></uploadExcelModal>
    <mergeDeptModal v-bind:mergeDeptModal="acceptDept"
                    v-on:saveOrgListener='saveOrgReturn'
                    ref="mdm"></mergeDeptModal>
    <changeDeptModal v-bind:mergeDeptModal="acceptDept"
                     v-on:saveOrgListener='saveOrgReturn'
                     ref="cdm"></changeDeptModal>
    <partnerChangeDeptModal v-bind:partnerModal="partnerInfo"
                            v-on:saveUserListener='saveUserReturn'
                            ref="pcdm"></partnerChangeDeptModal>
    <QRCode v-bind:qrcode="qrcodeNode"
            ref="qrCode"></QRCode>
  </div>
</template>

<script>
import addUserModal from "./addUser.vue";
import addOrgModal from "./addOrg.vue";
import uploadExcelModal from "./uploadExcel.vue";
import ztreeCore from "../../assets/js/zTree/jquery.ztree.core-3.5.min.js";
import ztreeAll from "../../assets/js/zTree/jquery.ztree.all.min.js";
import ztreeHide from "../../assets/js/zTree/jquery.ztree.exhide.js";
import mergeDeptModal from "./mergeDept.vue";
import changeDeptModal from "./changeDept.vue";
import partnerChangeDeptModal from "./partnerChangeDept.vue";
import QRCode from "../common/QRCode.vue";
export default {
  data() {
    return {
      loginInfo: {
        userId: window.localStorage.getItem("4_userId"),
        isLogin: window.localStorage.getItem("4_isLogin"),
        accountType: window.localStorage.getItem("4_accountType")
      },
      orgTreeData: [],
      rows: [],
      pageInfo: {
        pageNo: 1,
        pageSize: 10
      },
      addUserShow: false,
      addOrgShow: false,
      searchUserModel: {
        accountName: "",
        phone: "",
        accountType: ""
      },
      orgInfo: {
        orgId: "",
        optType: "",
        time: ""
      },
      userInfo: {
        orgId: "",
        userId: "",
        optType: "",
        time: ""
      },
      excelInfo: {
        orgId: "",
        optType: ""
      },
      accountType: window.localStorage.getItem("4_accountType"),
      acceptDept: {
        id: "",
        name: "",
        level: ""
      },
      partnerInfo: {
        id: "",
        name: ""
      },
      searchDeptModel: {
        deptName: ""
      },
      hiddenNodes: [],
      nodeList: [],
      qrcodeShow: false,
      qrcodeNode: {}
    };
  },
  components: {
    addUserModal,
    addOrgModal,
    uploadExcelModal,
    mergeDeptModal,
    changeDeptModal,
    partnerChangeDeptModal,
    QRCode
  },
  mounted: function () {
    this.loadOrgTreeData();
  },
  methods: {
    loadOrgTreeData: function () {
      //ztree基础属性设置
      var setting = {
        data: {
          simpleData: {
            enable: true
          }
        },
        callback: {
          onClick: this.zreeOnClick
        }
      };
      var body = {};
      var params = {};
      body.params = params;
      var _self = this;
      var url = _self.utilHelper.apiUrl + "/api/getDeptTree";
      _self.$http.post(url, body).then(
        (response) => {
          var data = response.body;
          var deptData = data.resData.nodesList;
          var result = data.result;
          $.fn.zTree.init($("#orgTree"), setting, deptData);
          //机构树加载成功后,加载经纪人数据
          _self.loadPartnerByDept();
        },
        (response) => {}
      );
    },
    openOrgModal(optType) {
      //获取选中的树节点
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var allNodes = treeObj.getNodes();
      var nodes = treeObj.getSelectedNodes();
      if (allNodes.length > 0 && nodes.length > 0) {
        if (optType == "A" && nodes[0].level >= 2) {
          layer.msg("机构层级最高3级，无法新增");
          return;
        }
        //得到第一个选中的节点（此处位单节点选中，因此直接获取即可）
        var selNode = nodes[0];
        //将节点信息及操作按钮的点击事件类型向下传递给子组件
        this.orgInfo.orgId = selNode.id;
        this.orgInfo.optType = optType;
        this.orgInfo.time = new Date().getMilliseconds();
        $("#addOrgModal").modal("show");
      } else {
        if (allNodes.length == 0 && optType == "A") {
          this.orgInfo.orgId = 0;
          this.orgInfo.optType = optType;
          this.orgInfo.time = new Date().getMilliseconds();
          $("#addOrgModal").modal("show");
        } else {
          //未选中任何部门，提示用户选择
          layer.msg("请选择一个部门 ", {
            time: 1000
          });
        }
      }
    },
    saveOrgReturn() {
      this.loadOrgTreeData();
    },
    delOrg: function () {
      var _self = this;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var nodes = treeObj.getSelectedNodes();
      if (nodes.length > 0) {
        //得到第一个选中的节点（此处位单节点选中，因此直接获取即可）
        var selNode = nodes[0];
        var id = selNode.id;
        var params = {};
        params["id"] = id;
        var body = {};
        body.params = params;
        layer.confirm(
          "您是否要删除该机构？",
          {
            btn: ["确定删除", "再考虑考虑"] //按钮
          },
          function () {
            var url = _self.utilHelper.apiUrl + "/api/delDept";
            _self.$http.post(url, body).then(
              (response) => {
                var data = response.body.resData;
                var result = data.result;
                var resData = data.resultMsg;
                //输出操作信息
                layer.msg(
                  resData,
                  {
                    time: 1000
                  },
                  function () {
                    if ("1" == result) {
                      _self.loadOrgTreeData();
                    }
                  }
                );
              },
              (response) => {}
            );
          },
          function () {}
        );
      } else {
        //未选中任何部门，提示用户选择
        layer.msg("请选择一个要删除的部门", {
          time: 1000
        });
      }
    },
    openUserModal(optType, userId) {
      //获取选中的树节点
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var nodes = treeObj.getSelectedNodes();
      if ("A" == optType) {
        //新增需要机构节点
        if (nodes.length > 0) {
          //得到第一个选中的节点（此处位单节点选中，因此直接获取即可）
          var selNode = nodes[0];
          this.userInfo.orgId = selNode.id;
          this.userInfo.optType = optType;
          this.userInfo.time = new Date().getMilliseconds();
          $("#addUserModal").modal("show");
        } else {
          //未选中任何部门，提示用户选择
          layer.msg("请选择一个部门 ", {
            time: 1000
          });
        }
      } else if ("U" == optType) {
        //修改无需机构节点，需得到会员ID
        this.userInfo.userId = userId;
        this.userInfo.optType = optType;
        this.userInfo.time = new Date().getMilliseconds();
        $("#addUserModal").modal("show");
      } else if ("M" == optType) {
        this.acceptDept.id = nodes[0].id;
        this.acceptDept.name = nodes[0].name;
        this.acceptDept.level = nodes[0].level;
        $("#mergeDeptModal").modal("show");
      } else if ("C" == optType) {
        this.acceptDept.id = nodes[0].id;
        this.acceptDept.name = nodes[0].name;
        this.acceptDept.level = nodes[0].level;
        $("#changeDeptModal").modal("show");
      }
    },
    saveUserReturn() {
      this.loadPartnerByDept();
    },
    uploadExcel(type) {
      this.excelInfo.optType = type;
      this.excelInfo.time = new Date().getTime();
      this.$refs.uploadExcelRef.initModal();
      if (type == "1") {
        //获取选中的树节点
        var treeObj = $.fn.zTree.getZTreeObj("orgTree");
        var allNodes = treeObj.getNodes();
        var nodes = treeObj.getSelectedNodes();
        if (allNodes.length > 0 && nodes.length > 0) {
          //得到第一个选中的节点（此处位单节点选中，因此直接获取即可）
          var selNode = nodes[0];
          //将节点信息及操作按钮的点击事件类型向下传递给子组件
          this.excelInfo.orgId = selNode.id;
          $("#uploadExcelModal").modal("show");
        } else {
          if (allNodes.length == 0) {
            this.excelInfo.orgId = 0;
            $("#uploadExcelModal").modal("show");
          } else {
            //未选中任何部门，提示用户选择
            layer.msg("请选择一个部门 ", {
              time: 1000
            });
          }
        }
      } else if (type == "2") {
        $("#uploadExcelModal").modal("show");
      }
    },
    updateUserStatus: function (id, status) {
      var _self = this;
      var params = {};
      params["id"] = id;
      params["status"] = status;
      var body = {};
      body.params = params;
      var desc = "启用";
      if ("1" == status) {
        desc = "禁用";
      }
      layer.confirm(
        "您是否要" + desc + "该用户？",
        {
          btn: ["确定" + desc + "", "再考虑考虑"] //按钮
        },
        function () {
          var url = _self.utilHelper.apiUrl + "/api/forbiddenOrNotPartner";
          _self.$http.post(url, body).then(
            (response) => {
              var data = response.body.resData;
              var result = data.result;
              var resData = data.resultMsg;
              //输出操作信息
              layer.msg(
                resData,
                {
                  time: 1000
                },
                function () {
                  if ("1" == result) {
                    _self.loadPartnerByDept();
                  }
                }
              );
            },
            (response) => {}
          );
        },
        function () {}
      );
    },
    initPass: function (id) {
      var _self = this;
      layer.confirm(
        "您确定要重置该用户密码？",
        {
          btn: ["确定重置", "再考虑考虑"] //按钮
        },
        function () {
          var params = {};
          params["id"] = id;
          var body = {};
          body.params = params;
          var url = _self.utilHelper.apiUrl + "/api/initPassword";
          _self.$http.post(url, body).then(
            (response) => {
              var data = response.body.resData;
              var result = data.result;
              var resData = data.resultMsg;
              var msg = "密码重置成功，密码已重置为：" + resData;
              //输出操作信息
              layer.open(
                {
                  content: msg,
                  area: "500px",
                  anim: 1,
                  icon: 6,
                  btn: ["复制密码", "确认"],
                  yes: function (index, layero) {
                    _self.$copyText(resData).then(
                      function (e) {
                        layer.msg("复制成功");
                      },
                      function (e) {
                        layer.msg("复制失败，请手动复制");
                      }
                    );
                  }
                },
                function () {
                  if ("1" == result) {
                    _self.loadPartnerByDept();
                  }
                }
              );
            },
            (response) => {}
          );
        },
        function () {}
      );
    },
    copy(message) {},
    loadPartnerByDept: function (pageNo) {
      //根据机构信息，获取用户
      var _self = this;
      var params = {};
      if (pageNo) {
        _self.pageInfo.pageNo = pageNo;
      }
      params["pageNo"] = _self.pageInfo.pageNo;
      params["pageSize"] = _self.pageInfo.pageSize;
      params["accountName"] = _self.searchUserModel.accountName;
      params["phone"] = _self.searchUserModel.phone;
      params["accountType"] = _self.searchUserModel.accountType;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      if (treeObj) {
        var node = treeObj.getSelectedNodes();
        if (node.length > 0) {
          var childNodes = treeObj.transformToArray(node);
          var nodes = "";
          var array = [];
          for (var i = 0; i < childNodes.length; i++) {
            //   nodes += parseInt(childNodes[i].id)+',';
            array.push(childNodes[i].id);
          }
          //params["deptIds"] = nodes.substring(0,nodes.lastIndexOf(','));
          params["deptIds"] = array;
          //获取机构门店组别
          _self.getQRCodeInfoByNode(node[0]);
        }
      }
      var url = this.utilHelper.apiUrl + "/api/getPartnerByDept";
      var body = {};
      body.params = params;
      this.$http.post(url, body).then(
        (response) => {
          var resData = response.body.resData.page;
          var totalPages = resData.totalPages;
          var rows = resData.rows;
          _self.rows = rows;
          //加载分页组件
          layui.laypage.render({
            elem: "laypage_div", //容器。值支持id名、原生dom对象，jquery对象,
            pages: totalPages, //总页数
            limit: 10,
            curr: _self.pageInfo.pageNo,
            count: resData.total,
            theme: "#09C", //皮肤
            first: "首页", //若不显示，设置false即可
            last: "尾页", //若不显示，设置false即可
            prev: "上一页", //若不显示，设置false即可
            next: "下一页", //若不显示，设置false即可
            layout: ["prev", "page", "next", "count"],
            jump: function (obj, first) {
              if (!first) {
                _self.pageInfo.pageNo = obj.curr;
                _self.loadPartnerByDept();
              }
            }
          });
        },
        (response) => {
          console.log("加载会员失败");
        }
      );
    },
    zreeOnClick: function (event, treeId, treeNode) {
      this.loadPartnerByDept();
    },
    deleteUser: function (id) {
      var _self = this;
      var url = this.utilHelper.apiUrl + "/api/delPartner";
      var params = {
        id: id,
        userId: window.localStorage.getItem("userId")
      };
      var body = {};
      body.params = params;
      layer.confirm(
        "确定要删除该人员？",
        {
          btn: ["确定", "取消"] //按钮
        },
        function () {
          _self.$http.post(url, body).then(
            (response) => {
              var resBody = response.body.resData;
              if (resBody.result == "1") {
                _self.loadPartnerByDept();
              }
              layer.alert(resBody.resultMsg);
            },
            (response) => {
              layer.alert("删除失败，系统异常");
            }
          );
        },
        function (index) {
          layer.close(index);
        }
      );
    },
    mergeModal: function (optType) {
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var nodes = treeObj.getSelectedNodes();
      if (nodes.length == 0) {
        layer.msg("请选择部门");
        return;
      }
      if (nodes[0].level == 0) {
        layer.msg("顶级部门不能修改");
        return;
      }
      var setting = {
        data: {
          simpleData: {
            enable: true
          }
        }
      };
      if (0 == optType) {
        this.acceptDept.id = nodes[0].id;
        this.acceptDept.name = nodes[0].name;
        this.acceptDept.level = nodes[0].level;
        if (treeObj) {
          $.fn.zTree.init($("#acceptTree"), setting, treeObj.getNodes());
        } else {
          this.$refs.mdm.loadOrgTreeData();
        }
        $("#mergeDeptModal").modal("show");
      } else if (1 == optType) {
        this.acceptDept.id = nodes[0].id;
        this.acceptDept.name = nodes[0].name;
        this.acceptDept.level = nodes[0].level;
        // if(treeObj){
        //     $.fn.zTree.init($("#changeTree"), setting, treeObj.getNodes());
        // }else{
        this.$refs.cdm.loadOrgTreeData();
        //}
        $("#changeDeptModal").modal("show");
      }
    },
    openDept: function (id, name) {
      var setting = {
        data: {
          simpleData: {
            enable: true
          }
        }
      };
      var _self = this;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");

      _self.partnerInfo.id = id;
      _self.partnerInfo.name = name;
      if (treeObj) {
        $.fn.zTree.init($("#partnerTree"), setting, treeObj.getNodes());
      } else {
        this.$refs.pcdm.loadOrgTreeData();
      }
      $("#changePartnerDeptModal").modal("show");
    },
    queryDetpByDeptName: function () {
      var _self = this;
      var node_type = "name";
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var allNode = treeObj.transformToArray(treeObj.getNodes());
      treeObj.hideNodes(allNode);

      var keywords = _self.searchDeptModel.deptName;
      if (keywords == "") {
        $("#orgTreeText").hide();
        treeObj.showNodes(allNode);
        treeObj.expandAll(false);
      } else {
        //_self.nodeList = treeObj.getNodesByParamFuzzy("text", keywords, null);
        _self.nodeList = treeObj.getNodesByFilter(_self.filterFunc);
        _self.nodeList = treeObj.transformToArray(_self.nodeList);
        for (var n in _self.nodeList) {
          if (_self.nodeList.hasOwnProperty(n)) {
            _self.findParent(treeObj, _self.nodeList[n]);
          }
        }
        if (_self.nodeList.length > 0) {
          $("#orgTreeText").hide();
          treeObj.showNodes(_self.nodeList);
        } else {
          $("#orgTreeText").show();
        }
      }
    },
    filterFunc: function (node) {
      var _self = this;
      var keywords = _self.searchDeptModel.deptName;
      if (node.name.indexOf(keywords) != -1) return true;
      return false;
    },
    findParent: function (treeObj, node) {
      var _self = this;
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      treeObj.expandNode(node, true, false, false);
      var pNode = node.getParentNode();
      if (pNode != null) {
        _self.nodeList.push(pNode);
        _self.findParent(treeObj, pNode);
      }
    },
    showQrCode() {
      var treeObj = $.fn.zTree.getZTreeObj("orgTree");
      var allNodes = treeObj.getNodes();
      var nodes = treeObj.getSelectedNodes();
      if (nodes.length == 0) {
        layer.msg("请选择一个部门 ", {
          time: 1000
        });
        return;
      } else {
        //获取数据，机构，门店，组别
        $("#qrCode").show();
        // 生成小程序码
        this.$refs.qrCode.wxqrcode();
      }
    },
    getQRCodeInfoByNode(node) {
      if (node.level == 0) {
        this.qrcodeNode.orgName = node.name;
        this.qrcodeNode.orgId = node.merchantId;
        this.qrcodeNode.qrCodeId = node.id;
        this.qrcodeNode.storeName = "";
        this.qrcodeNode.storeId = "";
        this.qrcodeNode.groupName = "";
        this.qrcodeNode.groupId = "";
      }
      if (node.level == 1) {
        this.qrcodeNode.storeName = node.name;
        this.qrcodeNode.storeId = node.id;
        this.qrcodeNode.qrCodeId = node.id;
        let pnode = node.getParentNode();
        if (pnode) {
          this.qrcodeNode.orgName = pnode.name;
          this.qrcodeNode.orgId = pnode.merchantId;
        }
        this.qrcodeNode.groupName = "";
        this.qrcodeNode.groupId = "";
      }
      if (node.level == 2) {
        this.qrcodeNode.groupName = node.name;
        this.qrcodeNode.groupId = node.id;
        this.qrcodeNode.qrCodeId = node.id;
        let snode = node.getParentNode();
        if (snode) {
          this.qrcodeNode.storeName = snode.name;
          this.qrcodeNode.storeId = snode.id;
          let pnode = snode.getParentNode();
          if (pnode) {
            this.qrcodeNode.orgName = pnode.name;
            this.qrcodeNode.orgId = pnode.merchantId;
          }
        }
      }
    }
  }
};
</script>